import { PageList } from "@mallfoundry/shared/data"
import { Store, StoreService } from "@mallfoundry/store"
import { useEffect, useState } from "react"

export function useStore(storeId: string) {
  const [loading, setLoading] = useState(false)
  const [store, setStore] = useState(new Store())

  useEffect(() => {
    setLoading(true)
    StoreService.getStore(storeId)
      .then(setStore)
      .finally(() => setLoading(false))
  }, [storeId])

  return {
    loading,
    store,
    setStore,
  }
}

interface UseStoreOptions {
  page?: number | string
  limit?: number | string
  ownerId?: string
  accountId?: string
  staffIds?: string | string[]
}

export function useStores(options: UseStoreOptions) {
  const { page, limit, ownerId, staffIds } = options
  const [loading, setLoading] = useState(false)

  const [pageStores, setPageStores] = useState(PageList.empty<Store>())

  useEffect(refresh, [page, limit, ownerId, staffIds])

  function refresh() {
    setLoading(true)
    StoreService.getStores(
      StoreService.createStoreQuery()
        .toBuilder()
        .ownerId(ownerId)
        .staffIds(staffIds)
        .build(),
    )
      .then(setPageStores)
      .finally(() => setLoading(false))
  }

  return {
    loading,
    refresh,
    ...pageStores,
  }
}
